package connect;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;

public class Broadcast extends Thread {
    static DatagramSocket broadcastSocket;
    static ArrayList<String> broadcastMsg = new ArrayList<>();
    static int broadFinish = 0;

    public ArrayList<String> getBroadcastMsg() {
        return broadcastMsg;
    }

    // 用来广播
    public Broadcast() throws Exception {
        // 创建发送端对象, 发送端自带默认端口号, 也可以指定端口号
        try {
            broadcastSocket = new DatagramSocket(8888);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void setBroadFinish() {
        broadFinish = 1;
    }

    public static void resetBroadFinish() {
        broadFinish = 0;
    }

    public static void release() {
        broadcastSocket.close();
        broadcastMsg.clear();
    }


    public static void sendBroadcastMessage(String m) throws Exception {
        //创建一个数据包对象封装数据
        byte[] buffer = m.getBytes();
        //获取正确IP
        GetTrueIP getIp = new GetTrueIP();
        InetAddress trueIp = getIp.getLocalHostExactAddress();
        DatagramPacket broadcastPack = new DatagramPacket(buffer, buffer.length, trueIp.getByName("255.255.255.255"), 8888);
        //发送数据
        broadcastSocket.send(broadcastPack);
        System.out.println("发送成功");
    }

    public static void callSendBroadMessage(String message) {
        try {
            sendBroadcastMessage(message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void receiveBroadcastMessage() throws Exception {
        //创建数据包对象
        byte[] buffer = new byte[1024 * 64];
        DatagramPacket receivePack = new DatagramPacket(buffer, buffer.length);
        //等待接收数据
        broadcastSocket.receive(receivePack);
        int len = receivePack.getLength();
        String getMsg = receivePack.getSocketAddress().toString().replaceAll("/", "") + " : " + new String(buffer, 0, len);
        if (!broadcastMsg.contains(getMsg))
            broadcastMsg.add(getMsg);
        System.out.println(broadcastMsg.get(0));
        //获取发送端的IP地址
        System.out.println("对方的IP地址：" + receivePack.getSocketAddress());
        //获取发送端的端口
        System.out.println("对方的端口：" + receivePack.getPort());
    }

    @Override
    public void run() {
        try {
            while (broadFinish != 1) {
                receiveBroadcastMessage();
            }
            System.out.println("广播结束");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
